import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Input, Drawer } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';
import { ModalForm, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import ProDescriptions from '@ant-design/pro-descriptions';
import UpdateForm from './UpdateForm'
import { rule, addRule, updateRule, removeRule } from '../service';
import { ProFormSelect } from '@ant-design/pro-form';
import { useImmer } from 'use-immer';

/**
 * 添加节点
 *
 * @param fields
 */
const handleAdd = async (fields) => {
  const hide = message.loading('正在添加');

  try {
    await addRule({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};
/**
 * 更新节点
 *
 * @param fields
 */

const handleUpdate = async (fields, currentRow) => {
  const hide = message.loading('正在修改');

  try {
    await updateRule({ ...currentRow, ...fields });
    hide();
    message.success('修改成功');
    return true;
  } catch (error) {
    hide();
    message.error('修改失败请重试！');
    return false;
  }
};
/**
 * 删除节点
 *
 * @param selectedRows
 */

const handleRemove = async (selectedRows) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  //console.log('selectedRows:', selectedRows)
  try {
    await removeRule({
      key: selectedRows.map((row) => row.userId),
    });
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

const TableList = () => {
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useImmer(false);
  /** 分布更新窗口的弹窗 */

  const [updateModalVisible, handleUpdateModalVisible] = useImmer(false);
  const [showDetail, setShowDetail] = useImmer(false);
  const actionRef = useRef();
  const [currentRow, setCurrentRow] = useImmer(undefined);
  const [selectedRowsState, setSelectedRows] = useImmer([]);
  /** 国际化配置 */

  const columns = [
    {
      title: '用户编号',
      dataIndex: 'userId',
      width: 100,
      tip: '用户编号是唯一的 key',
      render: (dom, entity) => {
        return (
          <span>
            {dom}
          </span>
        );
      },
    },
    {
      title: '用户名',
      width: 90,
      fixed: 'left',
      dataIndex: 'userName',
      valueType: 'textarea',
    },
    {
      title: '昵称',
      width: 90,
      dataIndex: 'nickName',
      valueType: 'textarea',
    },
    {
      title: '用户类型',
      width: 90,
      dataIndex: 'userType',
      valueEnum: {
        '00': '系统用户'
      },
    },
    {
      title: '邮箱',
      width: 140,
      dataIndex: 'email',
      valueType: 'textarea',
    },
    {
      title: '电话号码',
      width: 100,
      dataIndex: 'phonenumber',
      valueType: 'textarea',
    },
    {
      title: '性别',
      width: 50,
      dataIndex: 'sex',
      valueEnum: {
        0: '男',
        1: '女',
        3: '未知'
      },
    },
    {
      title: '用户头像',
      width: 200,
      hideInSearch: true,
      dataIndex: 'avatar',
      tip: '用户编号是唯一的 key',
      render: (_, record) => {
        return (
          <img src={record.avatar} maxheight="200"/>
        );
      },
    },
    {
      title: '密码',
      width: 90,
      hideInSearch: true,
      dataIndex: 'password',
      render: () => (<span>******</span>),
    },
    {
      title: '状态',
      width: 70,
      dataIndex: 'status',
      hideInSearch: true,
      valueEnum: {
        0: '正常',
        1: '停用',
      },
    },
    {
      title: '删除标记',
      width: 90,
      dataIndex: 'delFlag',
      hideInSearch: true,
      valueEnum: {
        0: '正常',
        2: '已删除',
      },
    },
    {
      title: '登录ip地址',
      width: 140,
      hideInSearch: true,
      dataIndex: 'loginIp',
      valueType: 'textarea',
    },
    {
      title: '上次登录时间',
      width: 140,
      sorter: true,
      hideInSearch: true,
      dataIndex: 'loginDate',
      valueType: 'dateTime',
    },
    {
      title: '上次登录时间',
      dataIndex: 'loginDate',
      valueType: 'dateRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            startLoginDate: value[0],
            endLoginDate: value[1],
          };
        },
      },
    },
    {
      title: '创建者',
      width: 90,
      dataIndex: 'createBy',
      hideInForm: true,
      valueType: 'textarea',
    },
    {
      title: '创建时间',
      width: 140,
      sorter: true,
      dataIndex: 'createTime',
      hideInSearch: true,
      valueType: 'dateTime',
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return defaultRender(item);
      },
    },
    {
      title: '修改者',
      width: 90,
      dataIndex: 'updateBy',
      hideInSearch: true,
      valueType: 'textarea',
    },
    {
      title: '修改时间',
      width: 140,
      sorter: true,
      hideInSearch: true,
      dataIndex: 'updateTime',
      valueType: 'dateTime',
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        return defaultRender(item);
      },
    },
    {
      title: '标记',
      width: 90,
      dataIndex: 'remark',
      valueType: 'textarea',
    },
    {
      title: '操作',
      width: 140,
      fixed: 'right',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="config"
          onClick={() => {
            handleUpdateModalVisible(true);
            setCurrentRow(record);
          }}
        >
          修改
        </a>
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable
        headerTitle="用户列表"
        actionRef={actionRef}
        rowKey="userId"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
        ]}
        request={rule}
        scroll={{ x: 2000 }}
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              已选择{' '}
              <a
                style={{
                  fontWeight: 600,
                }}
              >
                {selectedRowsState.length}
              </a>{' '}
              项 &nbsp;&nbsp;
            </div>
          }
        >
          <Button
            onClick={async () => {
              await handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
            }}
          >
            批量删除
          </Button>
        </FooterToolbar>
      )}
      <ModalForm
        title="新建规则"
        width="400px"
        open={createModalVisible}
        onFinish={async (value) => {
          console.log(value);
          handleModalVisible(false);
          const success = await handleAdd(value);

          if (success) {
            handleModalVisible(false);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      >
        <ProFormText
          label="用户名"
          rules={[{required: true,message: '必填项',},]}
          width="md"
          name="userName"
        />
        <ProFormText
          label="昵称"
          rules={[{required: true,message: '必填项',},]}
          width="md"
          name="nickName"
        />
        <ProFormText
          label="用户类型"
          rules={[{required: true,message: '必填项',},]}
          width="md"
          name="userType"
        />
        <ProFormText
          label="邮箱"
          rules={[{required: true,message: '必填项',},]}
          width="md"
          name="email"
        /> 
         <ProFormText
          label="电话号码"
          rules={[{required: true,message: '必填项',},]}
          width="md"
          name="phonenumber"
        />
        <ProFormSelect
           label="性别"
          width="md"
          name="sex"
          rules={[{required: true,message: '必填项',},]}
          valueEnum={{
            0: '男',
            1: '女',
            3: '未知'
          }}
        />
        <ProFormText
          label="密码"
          rules={[{required: true,message: '必填项',},]}
          width="md"
          name="password"
        />
        <ProFormText
          label="备注"
          rules={[{required: true,message: '必填项',},]}
          width="md"
          name="remark"
        />
      </ModalForm>
      <UpdateForm
        onSubmit={async (value) => {
          const success = await handleUpdate(value, currentRow);

          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);

            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        onVisibleChange={handleUpdateModalVisible}
        values={currentRow || {}}
      />

      <Drawer
        width={600}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.userId && (
          <ProDescriptions
            column={2}
            title={currentRow?.userId}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.userId,
            }}
            columns={columns}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

export default TableList;
